let http = {}
import { ElMessage } from 'element-plus'
import axios from 'axios'
import store from '@/stores';

let httpTimeOut = 30000

// 自定义异常处理方式
function custErrFun(err) {
    if(err.status == 500 || (err.response && err.response.status == 500)){
        ElMessage.error(err.response.data.msg || '请求失败，请检查网络或联系管理员');
    } else if(err.response.status == 403) {
        ElMessage.error(err.response.data.msg || '登录状态过期，请重新登录');
        window.location.href = '/'
        return
    } else if (err.response && err.response.status !== 200) {
        ElMessage.error(err.response.data.msg || '请求失败，请检查网络或联系管理员');
    } else {
        ElMessage.error('请求失败，请检查网络或联系管理员');
    }
}

// get 请求
http.get = function (url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
                params: params || {},
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'x-access-token': store.userStore.getToken
                },
                timeout: httpTimeOut
            })
            .then(res => {
                resolve(res)
            })
            .catch(err => {
                resolve(err)
                custErrFun(err)
            })
    });
};

// POST 请求
http.post = function (url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params, {
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'x-access-token': store.userStore.getToken
                },
                timeout: httpTimeOut
            })
            .then(res => {
                resolve(res)
            })
            .catch(err => {
                resolve(err)
                custErrFun(err)
            })
    });
};

export default http;
